package com.koron.ticket.work.logicticket.thirdticket.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.common.core.util.StringUtils;
import com.koron.ticket.work.common.bean.FifteenTables;
import com.koron.ticket.work.common.bean.FourteenTables;
import com.koron.ticket.work.common.bean.Print;
import com.koron.ticket.work.common.service.FifteenTablesService;
import com.koron.ticket.work.common.service.FourteenTablesService;
import com.koron.ticket.work.common.service.OrderChangeStatusService;
import com.koron.ticket.work.enums.TicketNodeStatus;
import com.koron.ticket.work.enums.TicketStatus;
import com.koron.ticket.work.enums.TicketType;
import com.koron.ticket.work.enums.WorkFlowType;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.bean.WorkPermitQuery;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workend.bean.WorkEndQuery;
import com.koron.ticket.work.workend.service.WorkEndService;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.bean.WorkFlowQuery;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workinfo.bean.WorkInfo;
import com.koron.ticket.work.workinfo.bean.WorkInfoQuery;
import com.koron.ticket.work.workinfo.service.WorkInfoService;
import com.koron.ticket.work.worklocation.service.WorkLocationService;
import com.koron.ticket.work.workmember.bean.WorkMember;
import com.koron.ticket.work.workmember.bean.WorkMemberQuery;
import com.koron.ticket.work.workmember.service.WorkMemberService;
import com.koron.ticket.work.workticket.bean.WorkTicket;
import com.koron.ticket.work.workticket.bean.WorkTicketQuery;
import com.koron.ticket.work.workticket.service.WorkTicketService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ThirdTicketService {

    @Autowired
    private FourteenTablesService fourteenTablesService;

    @Autowired
    private WorkMemberService workMemberService;

    @Autowired
    private WorkTicketService workTicketService;

    @Autowired
    private WorkInfoService workInfoService;

    @Autowired
    private WorkLocationService workLocationService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkEndService workEndService;

    @Autowired
    private FifteenTablesService fifteenTablesService;

    // 变更工单状态
    @Autowired
    private OrderChangeStatusService orderChangeStatusService;

    /**
     * 保存数据
     * 1. id为空是新增
     * 2. id不为空是更新
     *
     * @param factory
     * @param fourteenTables
     * @return Response对象
     * @version 1.0
     * @see Response
     * @see FifteenTables
     */
    @TaskAnnotation("writeSave")
    public Response writeSave(SessionFactory factory, FourteenTables fourteenTables) {
        String workTicketId = fourteenTablesService.writeSave(factory, fourteenTables);
        return Response.success(workTicketId);
    }

    @TaskAnnotation("getPrintData")
    public List<Print> getPrintData(SessionFactory factory, String workTicketId) {
        List<Print> result = new ArrayList<>();
        Print print = new Print();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = workTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();

        WorkMemberQuery workMemberQuery = new WorkMemberQuery();
        workMemberQuery.setWorkTicketId(workTicketId);
        List<WorkMember> workMemberList = workMemberService.getList(factory, workMemberQuery);

        List<String> memberlist = new ArrayList<>();
        memberlist.add(workTicket.getDirectorName());//工作负责人
        if (StringUtils.isNotEmpty(workMemberList)) {
//            workMemberListString = workMemberList.stream().map(WorkMember::getMemberName).collect(Collectors.joining(","));
            memberlist.addAll(workMemberList.stream().map(WorkMember::getMemberName).collect(Collectors.toList()));
        }
        String workMemberListString = memberlist.stream().collect(Collectors.joining(","));

        WorkInfoQuery workInfoQuery = new WorkInfoQuery();
        workInfoQuery.setWorkTicketId(workTicketId);
        WorkInfo workInfo = workInfoService.getSingle(factory, workInfoQuery);

        WorkPermitQuery workPermitQuery = new WorkPermitQuery();
        workPermitQuery.setWorkTicketId(workTicketId);
        WorkPermit workPermit = workPermitService.getSingle(factory, workPermitQuery);
        Opt<WorkPermit> workPermitOpt = Opt.ofNullable(workPermit);

        WorkFlowQuery workFlowQuery = new WorkFlowQuery();
        workFlowQuery.setWorkTicketId(workTicketId);
        List<WorkFlow> workFlowList = workFlowService.getList(factory, workFlowQuery);

        WorkEndQuery workEndQuery = new WorkEndQuery();
        workEndQuery.setWorkTicketId(workTicketId);
        WorkEnd workEnd = workEndService.getSingle(factory, workEndQuery);

        // 0.工作地点
        String locationStr = workLocationService.getLocationStr(factory, workTicketId);
        print.setLocationName(locationStr);

        // 1. 开票单位名称
        print.setUnitName(workTicket.getUnitName() + "第三种工作票");
        // 2. 工作票票号
        print.setCode(workTicket.getCode());
        // 3. 工作班成员
        print.setMemberNameListString(workMemberListString);
        // 4. 工作班成员数量
        print.setNumber(workTicket.getNumber());
        // 5. 工作内容
        print.setContent(workTicket.getContent());
        // 6. 计划开始时间
        if (workTicket.getEstimatedStartTime() != null) {
            // 兼容计划开始时间为空的情况
            print.setEstimatedStartTime(DateUtil.format(workTicket.getEstimatedStartTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        // 7. 计划结束时间
        if (workTicket.getEstimatedEndTime() != null) {
            // 兼容计划结束时间为空的情况
            print.setEstimatedEndTime(DateUtil.format(workTicket.getEstimatedEndTime(), "yyyy年MM月dd日 HH时mm分"));
        }
        // 8. 安全措施
        print.setSafetyMeasures(workInfo.getSafetyMeasures());
        if (status >= TicketStatus.PERMIT.getStatus()) {
            // 9. 许可工作时间
            print.setWorkTime(Opt.ofNullable(DateUtil.format(workPermitOpt.map(WorkPermit::getWorkTime).orElse(null), "yyyy年MM月dd日 HH时mm分")).orElse(""));
            // 10. 工作待许可-工作许可人/工作负责人/工作跟踪责任人
            for (WorkFlow workFlow : workFlowList) {
                if (workFlow.getStatus() == TicketStatus.PERMIT.getStatus()) {
                    String type = workFlow.getType();
                    // 20211213：type由"工作许可人"变更为"name0"
                    if (type.equals("name0")) {
                        print.setPermitName(workFlow.getName());
                    } // 20211213：type由"工作负责人"变更为"name1"
                    else if (type.equals("name1")) {
                        print.setDirectorNameForPermit(workFlow.getName());
                    } // 20211213：type由"工作跟踪负责人"变更为"name2"
                    else if (type.equals("name2")) {
                        print.setPermitTrackName(workFlow.getName());
                    }
                }
            }
        }
        if (status >= TicketStatus.TICKET_END.getStatus()) {
            // 11. 工作票结束时间
            Date date = Opt.ofNullable(workEnd).map(WorkEnd::getEndTime).orElse(null);
            Opt<String> optdate = Opt.ofNullable(DateUtil.format(date, "yyyy年MM月dd日 HH时mm分"));
            print.setEndTimeForTicketEnd(optdate.orElse(""));
            // 12. 工作许可人/工作负责人
            for (WorkFlow workFlow : workFlowList) {
                if (workFlow.getStatus() == TicketStatus.TICKET_END.getStatus()) {
                    String type = workFlow.getType();
                    // 20211213：type由"工作许可人"变更为"name1"
                    if (type.equals("name1")) {
                        print.setPermitNameForTicketEnd(workFlow.getName());
                    } // 20211213：type由"工作负责人"变更为"name0"
                    else if (type.equals("name0")) {
                        print.setDirectorNameForTicketEnd(workFlow.getName());
                    }
                }
            }
            // 13. 备注
            print.setDescription(Opt.ofNullable(workEnd).map(WorkEnd::getEndDescription).orElse(""));
        }
//        if (status >= TicketStatus.TICKET_END.getStatus()) {
//            Opt<String> optdate = Opt.of(DateUtil.format(workEnd.getEndTime(), "yyyy年MM月dd日 HH时mm分"));
//            print.setEndTimeForTicketEnd(optdate.orElse(""));
//        }
        result.add(print);

        return result;
    }

    @TaskAnnotation("writeSubmit")
    public Response writeSubmit(SessionFactory factory, FourteenTables fourteenTables) {
        // 1. 先生成工作票票号
        WorkTicket workTicket = fourteenTables.getWorkTicket();
        String code = fifteenTablesService.getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), workTicket.getType());
        workTicket.setCode(code);
        // 20211202: 更新预览标志
        workTicket.setPreviewFlag(1);
        String workTicketId = fourteenTablesService.writeSubmitByWorkFlowTypeAndStatus(
                factory, fourteenTables, WorkFlowType.ThirdTicket.getWorkFlow(), TicketStatus.PERMIT.getStatus());
        return Response.success(workTicketId);
    }

    @TaskAnnotation("permitSave")
    public Response permitSave(SessionFactory factory, WorkPermit workPermit) {
        fifteenTablesService.permitSave(factory, workPermit);
        return Response.success("待许可-保存成功");
    }

    @TaskAnnotation("ticketEndSave")
    public Response ticketEndSave(SessionFactory factory, WorkEnd workEnd) {
        fifteenTablesService.endSaveWithStatus(factory, workEnd, TicketStatus.TICKET_END.getStatus());
        return Response.success("工作票待终结-提交/保存成功");
    }

    @TaskAnnotation("workflowUpdate")
    public Response workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        Integer operation = redirectQuery.getOperation();
        String workTicketId = redirectQuery.getDataId();
        WorkTicketQuery workTicketQuery = new WorkTicketQuery();
        workTicketQuery.setId(workTicketId);
        WorkTicket workTicket = workTicketService.getSingle(factory, workTicketQuery);
        Integer status = workTicket.getStatus();
        // 1. 如果被驳回，返回对应状态，并删除对应的信息
        if (operation == 1) {
            String rejectNodeCode = redirectQuery.getRejectNodeCode();
            rejectNodeCode = rejectNodeCode.replace("call-", "");
            // 1.1 如果被驳回到填写状态
            if (rejectNodeCode.equals(TicketNodeStatus.WRITE.getNodeName())) {
                Integer rejectStatus = TicketStatus.WRITE.getStatus();
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
            } // 1.2 如果被驳回到待许可状态
            else if (rejectNodeCode.equals(TicketNodeStatus.PERMIT.getNodeName())) {
                Integer rejectStatus = TicketStatus.PERMIT.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
                // 20211202: 仅待许可状态需要保存-预览-提交
                workTicket.setPreviewFlag(1);
            }
            // 1.3 更新工作票状态
            workTicketService.update(factory, workTicket);
        } // 2. 如果通过，工作票进入对应的状态，并根据状态保存相应的数据
        else if (operation.equals(32)) {
            String formVariables = redirectQuery.getFormVariables();
//            Map<String, String> infoMap = TextUtil.toMapFromString(formVariables);
            // 2.1 如果是待许可状态，保存签名信息，及待许可信息
            if (status.equals(TicketStatus.WRITE.getStatus())) {
//                workPermitService.insertByMap(factory, infoMap, status);
                if (StrUtil.isBlank(workTicket.getCode())) {
                    String code = fifteenTablesService.getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), workTicket.getType());
                    workTicket.setCode(code);
                }
                workTicket.setStatus(TicketStatus.PERMIT.getStatus());
            }
            // 2.2 将工作票状态更新为工作票待终结
            if (status.equals(TicketStatus.PERMIT.getStatus())) {
                WorkPermit workPermit = JSONObject.parseObject(formVariables, WorkPermit.class);
                workPermit.setPermitTime(new Date());
                workPermit.setId(workPermit.getWorkPermitId());
                workPermit.setPermitTime(new Date());
                workPermitService.save(factory, workPermit);
                // 保存签名信息
                List<WorkFlow> workFlowList = workPermit.getWorkFlowList();
                if (workFlowList != null && workFlowList.size() > 0) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFLow.setId(workFLow.getWorkFlowId());
                        workFlowService.save(factory, workFLow);
                    }
                }
                workTicket.setStatus(TicketStatus.TICKET_END.getStatus());
                // 许可后变更工单状态为执行中
                orderChangeStatusService.changeOrderStatus(workTicket.getOrderType(), workTicket.getOrderId());
            }
            if (status.equals(TicketStatus.TICKET_END.getStatus())) {
                workTicket.setStatus(TicketStatus.ARCHIVED.getStatus());
            }
            workTicketService.update(factory, workTicket);
        } else if (operation == 256) {
            Integer rejectStatus = TicketStatus.WRITE.getStatus();
            workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
            fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
            workTicket.setStatus(rejectStatus);
            workTicketService.update(factory, workTicket);
        } else {
            return Response.fail("操作类型为：" + operation + ",请联系运维人员");
        }

        return Response.success("回调成功");
    }

    @TaskAnnotation("workflowUpdateEnd")
    public Response workflowUpdateEnd(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        fifteenTablesService.workflowUpdateEnd(factory, redirectQuery);
        return Response.success("工作票已归档");
    }

    @TaskAnnotation("workflowUpdateCancel")
    public Response workflowUpdateCancel(SessionFactory factory, RedirectQuery redirectQuery) {
        fifteenTablesService.workflowUpdateCancel(factory, redirectQuery);
        return Response.success("工作票已作废");
    }

    public FourteenTables add() {
        FourteenTables fourteenTables = fourteenTablesService.addByType(TicketType.ThirdTicket.getType());
        return fourteenTables;
    }


    public FourteenTables getById(SessionFactory factory, String id) {
        FourteenTables fourteenTables = fourteenTablesService.getById(factory, id);
        return fourteenTables;
    }

    public void deleteById(SessionFactory factory, String id) {
        fourteenTablesService.deleteById(factory, id);
    }

}
